<?php

namespace App\Models\Sanctum;

use App\Traits\ModelTrait;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\PersonalAccessToken as SanctumPersonalAccessToken;

class PersonalAccessToken extends SanctumPersonalAccessToken
{
    use ModelTrait;
    public static function findToken($token)
    {
        if (!str_contains($token, '|')) {
            return Cache::remember('CacheUserToken:'.$token, now()->addMinutes(60), function () use ($token) {
                return static::query()->where('token', hash('sha256', $token))->first();
            });
        }
        [$id, $token] = explode('|', $token, 2);
        $instance = Cache::remember('CacheUserToken:'.$id, now()->addMinutes(60), function () use ($id) {
            return static::query()->find($id);
        });
        if ($instance) {
            return hash_equals($instance->token, hash('sha256', $token)) ? $instance : null;
        }
        return null;
    }

    public static function clearUserToken($request)
    {
        $token = str_replace('Bearer ', '', $request->server('HTTP_AUTHORIZATION'));
        if (!str_contains($token, '|')) {
            Cache::forget('CacheUserToken:'.$token);
        }
        [$id] = explode('|', $token, 2);
        Cache::forget('CacheUserToken:'.$id);
    }
}
